# coding=utf-8
import tensorflow as tf
import mnist_inference
import os
from tensorflow.contrib.layers import l2_regularizer
from tensorflow.examples.tutorials.mnist import input_data

REGULARAZTION_RATE = 0.0001
LEARN_RATE_BASE = 0.8
LEARN_RATE_DECAY = 0.99
TRAINING_STEP = 30000
MOVING_AVERAGE_DECAY = 0.99
BATCH_SIZE = 100
CKPT_PATH = './output'
CKPT_NAME = "trained_variables.ckpt"


def train(mnist):
    # 需要输入的图片数据
    x = tf.placeholder(tf.float32, [None, mnist_inference.INPUT_NODE], name="x-input")
    # 需要输入的图片的结果数据
    y_ = tf.placeholder(tf.float32, [None, mnist_inference.OUTPUT_NODE], name='y-input')

    # 加上正则化、防止过拟合
    regularizer = l2_regularizer(REGULARAZTION_RATE)
    y = mnist_inference.inference(x, regularizer)

    cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=y, labels=tf.argmax(y_, 1))
    cross_entropy_mean = tf.reduce_mean(cross_entropy)

    # ls为正则化的增量
    ls = tf.add_n(tf.get_collection("losses"))
    # 交叉熵平均值 + 正则化
    loss = cross_entropy_mean + ls

    # 用来记录当前训练步骤的变量
    global_step = tf.Variable(0, trainable=False)

    # 指数衰减学习率
    learning_rate = tf.train.exponential_decay(LEARN_RATE_BASE,
                                               global_step,
                                               mnist.train.num_examples / BATCH_SIZE,
                                               LEARN_RATE_DECAY)

    variable_averages = tf.train.ExponentialMovingAverage(MOVING_AVERAGE_DECAY, global_step)
    variables_averages_op = variable_averages.apply(tf.trainable_variables())
    train_step = tf.train.GradientDescentOptimizer(learning_rate=learning_rate).minimize(loss, global_step=global_step)
    with tf.control_dependencies([train_step, variables_averages_op]):
        train_op = tf.no_op(name='train')

    saver = tf.train.Saver()
    with tf.Session() as sess:
        init = tf.global_variables_initializer()
        sess.run(init)
        for i in range(TRAINING_STEP):
            xs, ys = mnist.train.next_batch(BATCH_SIZE)
            loss_value = sess.run([train_op, loss, learning_rate, global_step, ls], feed_dict={x: xs, y_: ys})
            if i % 1000 == 0:
                print(loss_value)
                # 讲训练的数据进行储存
                saver.save(sess, os.path.join(CKPT_PATH, CKPT_NAME), global_step=global_step)


def main(args=None):
    mnist = input_data.read_data_sets(mnist_inference.MNIST_PATH, one_hot=True)
    train(mnist)


if __name__ == '__main__':
    tf.app.run()
